exports.APIServer = function(resourcePath) {

  //本地存储
  const Store = require('electron-store');
  const store = new Store();

  //设置Express服务器
  var express = require('express')
  var app = express()

  //设置跨域访问
  app.all('*', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "X-Requested-With");
      res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
      res.header("X-Powered-By",'3.2.1')
      res.header("Content-Type", "application/json;charset=utf-8");
      next();
  });

  //接口解析数据
  // app.get('/extract', function (req, res) {
  //
  //   const child_process = require('child_process')
  //
  //   if(!req.query.url){
  //     res.send('[Error]请输入内容链接')
  //     return
  //   }
  //
  //   var workerProcess = child_process.exec(resourcePath + '/wx ' + req.query.url + ' ' + store.get('baseDir'), function (error, stdout, stderr) {
  //     if (error) {
  //       console.log(error.stack)
  //       console.log('Error code: ' + error.code)
  //       console.log('Signal received: ' + error.signal)
  //     }
  //     console.log('stdout: ' + stdout)
  //     console.log('stderr: ' + stderr)
  //   })
  //
  //   workerProcess.on('exit', function (code) {
  //     console.log('子进程已退出，退出码 ' + code)
  //     res.send('[INFO]采集成功')
  //   })
  //
  //
  // })

  // 设置保存目录
  app.get('/chooseDir', async function (req, res){
    const {dialog} = require('electron')

    await dialog.showOpenDialog({
      properties: ['openDirectory']
    }).then(result => {
      console.log(result.canceled)

      if(!result.canceled){
        store.set("baseDir",result.filePaths[0])

      }
      console.log(result.filePaths)
    }).catch(err => {
      console.log(err)
    })


    res.send('设置成功')


    })

  //获取保存目录
  app.get('/getDir', function (req, res){
    res.send(store.get('baseDir'))
  })

  //打开新页面，获取完整html文档,关闭窗口
  app.get('/newWindow', function (req, res){
    const { BrowserWindow } = require('electron')
    const path = require('path')

    const win = new BrowserWindow({ width: 400, height: 300 ,
      webPreferences: {
        preload: path.join(__dirname, 'preload.js'),
        nodeIntegration: true, //渲染进程允许调用NodeJS
        images: false,
        webSecurity: false,//禁用同源策略
      }
    })

    //爬虫链接
    url = req.query.url

    win.loadURL(url)

    res.send('newWindow')
  })



  var server = app.listen(6789, function () {
    // var host = server.address().address
    // var port = server.address().port
    //
    // console.log('应用实例，访问地址为 http://%s:%s', host, port)
  })

  //打开文件
  app.get('/openFolder', function (req, res) {
    const {shell} = require('electron') // deconstructing assignment

    shell.showItemInFolder(store.get('baseDir'))

    res.send("打开文件")
  })

}
